package org.basis.algorithm.graph;

import org.basis.algorithm.graph.common.Node;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * 图的宽度优先遍历(宽度优先靠队列)
 *
 * @author Mr_wenpan@163.com 2021/12/23 14:10
 */
public class Bfs {

    public static void main(String[] args) {

    }

    public static void bfs(Node node) {
        LinkedList<Node> queue = new LinkedList<>();
        HashSet<Node> set = new HashSet<>();
        queue.add(node);
        set.add(node);

        while (!queue.isEmpty()) {
            // 从队列里弹出，弹出就打印
            Node poll = queue.poll();
            System.out.print(poll.value + "   ");
            // 把它紧邻的节点全部加到队列
            List<Node> nexts = poll.nexts;
            for (Node next : nexts) {
                if (!set.contains(next)) {
                    queue.add(next);
                    set.add(next);
                }
            }
        }
    }

}
